因為要擺放家具,所以首要的重要功能就是需要拖曳家具,第二天先拆解這個功能出來練習
目標是拖曳emoji進去卡片之中
首先要安裝cdk
npm install @angular/cdk
再來需要在app.module.ts引用DragDropModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DragDropModule } from '@angular/cdk/drag-drop'
import { AppComponent } from './app.component';
import { ResizableDirective } from './resizable.directive';
import { RotatableDirective } from './rotatable.directive';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
DragDropModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
引用完之後,在app.component.ts,建立變數跟方法
import { CdkDragEnd } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';
interface CardElement {
type: string;
position: { x: number; y: number };
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'card';
elements: string[] = ['🎄', '🎅', '🎁', '❄️', '🦌', '🔔'];
card: CardElement[] = [];
addToCard(item: string) {
this.card.push({
type: item,
position: { x: 10, y: 10 } // 初始位置
});
}
onDragEnded(event: CdkDragEnd, index: number) {
}
}
之後就可以繼續完成html跟scss的部分了
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
<h3>元素</h3>
<div class="elements-list">
<div class="element-box" *ngFor="let item of elements" cdkDrag [cdkDragDisabled]="true"
(click)="addToCard(item)">
{{item}}
</div>
</div>
</div>
<div class="col-md-9">
<h3>聖誕卡片</h3>
<div class="card-area">
<div *ngFor="let item of card; let i = index" class="card-element" cdkDrag
(cdkDragEnded)="onDragEnded($event, i)" [style.left.px]="item.position.x" [style.top.px]="item.position.y">
{{item.type}}
</div>
</div>
</div>
</div>
</div>
.elements-list,
.card-area {
border: solid 1px #ccc;
min-height: 60px;
background: white;
border-radius: 4px;
overflow: hidden;
display: block;
}
.card-area {
height: 400px;
position: relative;
background-image: linear-gradient(90deg, rgba(211,211,211,0.5) 1px, transparent 1px),
linear-gradient(rgba(211,211,211,0.5) 1px, transparent 1px);
background-size: 50px 50px;
}
.element-box {
// padding: 20px 10px;
border-bottom: solid 1px #ccc;
color: rgba(0, 0, 0, 0.87);
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
cursor: move;
background: white;
font-size: 14px;
}
.card-element {
position: absolute;
cursor: move;
display: inline-block;
font-size: 24px;
border: 1px solid black;
}